﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Common;
using Nova_DAL;
using System.Text;
using System.Globalization;

public partial class DelStorage_DelStoragePage1 : System.Web.UI.Page
{
    Nova_DAL.DbHelper dbHelper = new DbHelper();
    string strSQL = "";
    DbCommand cmd = null;
    //string strPID = "";
    //ArrayList ArrayPID = new ArrayList();
    //ArrayList ArrayNum = new ArrayList();
    //DataTable dtone = null;
    //int iback = 0;

    //DataSet ds = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
            BindGridDate();

        }
    }

    private void BindGrid()
    {
        string WCode = Request.Cookies["WType"].Value;
        strSQL = @"select distinct TDS.StockNo from dbo.TBill_DelStorage as TDS 
                        left join dbo.TDelStorage_List as TDL ON TDS.STOCKNO=TDL.STOCKNO
                        WHERE TDL.NUM<>TDL.ACT_NUM and TDS.Bill_Status=0 and (TDL.TS02='" + WCode + "' or 'FSSC'='" + WCode + "')";
        DateTime date = System.DateTime.Now;
        int year = date.Year;
        string month = Convert.ToString(date.Month).PadLeft(2, '0');
        string day = Convert.ToString(date.Day).PadLeft(2, '0') ;
        string strDate = Convert.ToString(year) + "-" + month + "-" + day;

        //if (string.IsNullOrEmpty(txtCDTS.Text) && string.IsNullOrEmpty(txtCDTE.Text))
        //{
        //    strSQL += "   and convert(varchar(10) ,TDS.CDT,120)='" + strDate + "'";

        //}
        //else 
        if (txtCDTS.Text != "")
        {
            strSQL = strSQL + " and convert(varchar(10) ,TDS.CDT,120)>='" + txtCDTS.Text + "'";
        }
        if (txtCDTE.Text != "")
        {
            strSQL = strSQL + " and convert(varchar(10) ,TDS.CDT,120)<= '" + txtCDTE.Text + "'";
        }
        if (txtStockNo.Text != "")
        {
            strSQL += @" and TDS.StockNo like '%"+txtStockNo.Text.Trim()+"%' ";
        }
        cmd = dbHelper.GetSqlStringCommond(strSQL);

        gvStock.DataSource = dbHelper.ExecuteDataSet(cmd);
        gvStock.DataBind();

    }

    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        BindGrid();
        gv.DataSource = null;
        gv.DataBind();
    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            LinkButton lbtn_Mat_Code = (LinkButton)e.Row.FindControl("lbtn_Mat_Name");

            string updateUrl = string.Format("javascript: document.getElementById('{1}').value=window.showModalDialog('SearchStock.aspx?Ram=" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "&strMatCode={0}&delPID={2}', window, 'dialogWidth=700px;dialogHeight=500px;scroll:no;resizable:no;status:0;');document.URL=location.href;", lbtn_Mat_Code.CommandArgument.ToString(), hidden.ClientID, gv.DataKeys[e.Row.RowIndex].Value.ToString());
            lbtn_Mat_Code.Attributes.Add("onclick", updateUrl);

        }
    }

    protected void ibtndelete_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton button = (ImageButton)sender;
        int guid = Convert.ToInt32(button.CommandArgument.ToString());
        strSQL = @"delete from Tmp_DelStorage where Guid=" + guid;
        cmd = this.dbHelper.GetSqlStringCommond(strSQL);
        dbHelper.ExecuteNonQuery(cmd);
        BindGridDate();

    }
    protected void ibtnMerge_Click(object sender, ImageClickEventArgs e)
    {
        gv.DataSource = null;
        gv.DataBind();
        StringBuilder sbStock = new StringBuilder();
        for (int i = 0; i < gvStock.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gvStock.Rows[i].FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                sbStock.Append("'" + gvStock.DataKeys[i].Value.ToString() + "'" + ",");
            }
        }

        Label1.Text = "";
        if (sbStock.Length == 0)
        {
            Label1.Text = "请选择要合并的出库单！";
        }
        else
        {
            MergeDelStorageTable(sbStock);
            //DELSession();
        }
    }

    private void MergeDelStorageTable(StringBuilder sbStock)
    {
        string WCode = Request.Cookies["WType"].Value;
        //DynamicState01=1 表示该明细已经全部出库了
        strSQL = @" Select  TBM.Mat_Name,TBM.Mat_Code,TDS.Num,ISNULL(TDS.Act_Num,0) as Act_Num,TDS.PID from TDelStorage_List TDS LEFT JOIN TBase_Material TBM ON TDS.Mat_Code = TBM.Mat_Code
                     where TDS.StockNo in (" + sbStock.ToString().TrimEnd(',') + ") and DynamicState01 is null and (TDS.TS02='" + WCode + "' or 'FSSC'='" +WCode+"') order by TDS.Mat_Code";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataTable dt = dbHelper.ExecuteDataTable(cmd);

        DataTable dtMerge = new DataTable();
        dtMerge.Columns.Add("Mat_Name", typeof(string));
        dtMerge.Columns.Add("Mat_Code", typeof(string));
        dtMerge.Columns.Add("Num", typeof(decimal));
        dtMerge.Columns.Add("Act_Num", typeof(decimal));
        dtMerge.Columns.Add("PID", typeof(string));

        string Mat_Code = System.Guid.NewGuid().ToString();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (Mat_Code == dt.Rows[i][1].ToString())
            {
                dtMerge.Rows[dtMerge.Rows.Count - 1][4] += "$" + dt.Rows[i][4].ToString();
                dtMerge.Rows[dtMerge.Rows.Count - 1][2] = Convert.ToDecimal(dtMerge.Rows[dtMerge.Rows.Count - 1][2]) + Convert.ToDecimal(dt.Rows[i][2]);
                dtMerge.Rows[dtMerge.Rows.Count - 1][3] = Convert.ToDecimal(dtMerge.Rows[dtMerge.Rows.Count - 1][3]) + Convert.ToDecimal(dt.Rows[i][3]);

            }
            else
            {
                Mat_Code = dt.Rows[i][1].ToString();
                dtMerge.Rows.Add(new object[] { dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), Convert.ToDecimal(dt.Rows[i][2]), Convert.ToDecimal(dt.Rows[i][3]), dt.Rows[i][4].ToString() });
            }
        }


        gv.DataSource = dtMerge;
        gv.DataBind();
    }

    protected void ibt_reset_Click(object sender, ImageClickEventArgs e)
    {
        ClearGrid();
    }

    protected void ibtn_jianxian_Click(object sender, ImageClickEventArgs e)
    {
        cmd = dbHelper.GetStoredProcCommond("SP_START_OUTPUT");
        dbHelper.ExecuteNonQuery(cmd);

        //DataTable dtCheck = new DataTable();
        //dtCheck.Columns.Add("DetailPID", typeof(string));
        //dtCheck.Columns.Add("Act_Num", typeof(decimal));
        //dtCheck.Columns.Add("Num", typeof(decimal));

        DataTable dtOut = new DataTable();
        dtOut.Columns.Add("STORE_PID", typeof(string));
        dtOut.Columns.Add("MAT_NUM", typeof(decimal));
        dtOut.Columns.Add("DETAIL_PID", typeof(Int64));

        dtOut.Columns.Add("TRAY_ID", typeof(string));
        dtOut.Columns.Add("ContainerID", typeof(string));
        dtOut.Columns.Add("SEC_MAT_ID", typeof(string));

        string detailPID = "";
        for (int i = 0; i < gvDate.Rows.Count; i++)
        {
            Label labTray_ID = (Label)gvDate.Rows[i].FindControl("lab_Tray_ID");
            string strTray_ID = labTray_ID.Text.ToString();

            Label labContainerID = (Label)gvDate.Rows[i].FindControl("lab_ContainerID");
            string strContainerID = labContainerID.Text.ToString();

            Label labSEC_MAT_ID = (Label)gvDate.Rows[i].FindControl("lab_SEC_MAT_ID");
            string strSEC_MAT_ID = labSEC_MAT_ID.Text.ToString();



            detailPID = gvDate.Rows[i].Cells[6].Text.ToString();
            String[] strs = detailPID.Split('$');

            if (strs.Length == 1)
            {
                //cmd = dbHelper.GetStoredProcCommond("SP_INSERT_FOR_OUT");
                //dbHelper.AddInParameter(cmd, "@STORE_PID", DbType.String, gvDate.DataKeys[i].Value.ToString());
                //TextBox txtNum = (TextBox)gvDate.Rows[i].FindControl("txtNum");
                //dbHelper.AddInParameter(cmd, "@MAT_NUM", DbType.Decimal, txtNum.Text.ToString());
                //dbHelper.AddInParameter(cmd, "@DETAIL_PID", DbType.Int64, detailPID);
                //dbHelper.ExecuteNonQuery(cmd);

                TextBox txtNum = (TextBox)gvDate.Rows[i].FindControl("txtNum");
                dtOut.Rows.Add(new object[] { gvDate.DataKeys[i].Value.ToString(), Convert.ToDecimal(txtNum.Text), Convert.ToInt64(detailPID), strTray_ID, strContainerID, strSEC_MAT_ID });
            }
            else
            {
                TextBox txtNum = (TextBox)gvDate.Rows[i].FindControl("txtNum");
                Label lbl_Num = (Label)gvDate.Rows[i].FindControl("lbl_Num");
                if (decimal.Compare(Convert.ToDecimal(txtNum.Text.Trim()), Convert.ToDecimal(lbl_Num.Text))!=0)
                {
                    this.Label1.Text = "";
                    this.Label1.Text = "合并单号：" + detailPID + "出库数量与实际数量不符合，请重新合并单据或者填写正确的出库数量！";
                    return;
                }
                

                //DataRow[] drw = dtCheck.Select("DetailPID='" + detailPID + "'");
                //if (drw.Length == 0)
                //{
                //    dtCheck.Rows.Add(new object[] { detailPID, Convert.ToDecimal(txtNum.Text.ToString()) });
                //}
                //else
                //{
                //    drw[0][1] = Convert.ToDecimal(drw[0][1]) + Convert.ToDecimal(txtNum.Text.ToString());
                //}
                for (int j = 0; j < strs.Length; j++)
                {

                    //cmd = dbHelper.GetStoredProcCommond("SP_INSERT_FOR_OUT");
                    //dbHelper.AddInParameter(cmd, "@STORE_PID", DbType.String, gvDate.DataKeys[i].Value.ToString());
                    //dbHelper.AddInParameter(cmd, "@MAT_NUM", DbType.Decimal, num);
                    //dbHelper.AddInParameter(cmd, "@DETAIL_PID", DbType.Int64, Convert.ToInt64(strs.GetValue(j)));
                    //dbHelper.ExecuteNonQuery(cmd);
                    DataRow[] drwd = dtOut.Select("DETAIL_PID=" + Convert.ToInt64(strs.GetValue(j)));
                    if (drwd.Length == 0)
                    {
                        strSQL = @"select Num from dbo.TDelStorage_List where PID=" + Convert.ToInt64(strs.GetValue(j));
                        cmd = dbHelper.GetSqlStringCommond(strSQL);
                        decimal num = Convert.ToDecimal(dbHelper.ExecuteScalar(cmd));

                        dtOut.Rows.Add(new object[] { gvDate.DataKeys[i].Value.ToString(), num, Convert.ToInt64(strs.GetValue(j)), strTray_ID, strContainerID, strSEC_MAT_ID });

                    }
                }
            }

        }

        //this.Label1.Text = "";
        //for (int i = 0; i < dtCheck.Rows.Count; i++)
        //{
        //    for (int j = 0; j < gv.Rows.Count; j++)
        //    {
        //        if (dtCheck.Rows[i][0].ToString() == gv.DataKeys[j].Value.ToString()
        //            && Convert.ToDecimal(dtCheck.Rows[i][1]) != (Convert.ToDecimal(gv.Rows[j].Cells[4].Text) - Convert.ToDecimal(gv.Rows[j].Cells[5].Text)))
        //        {
        //            this.Label1.Text = "合并单号：" + dtCheck.Rows[i][0].ToString() + "出库数量与实际数量不符合，请重新合并单据或者填写正确的出库数量！";
        //            return;
        //        }
        //        else
        //        {
        //            continue;
        //        }
        //    }
        //}

        int iFlag = 0;
        for (int i = 0; i < dtOut.Rows.Count; i++)
        {
            if (dtOut.Rows[i][3].ToString().Length == 4)
            {
                iFlag = 1;
                cmd = dbHelper.GetStoredProcCommond("SP_INSERT_FOR_OUT");
                dbHelper.AddInParameter(cmd, "@STORE_PID", DbType.String, dtOut.Rows[i][0].ToString());
                dbHelper.AddInParameter(cmd, "@MAT_NUM", DbType.Decimal, Convert.ToDecimal(dtOut.Rows[i][1]));
                dbHelper.AddInParameter(cmd, "@DETAIL_PID", DbType.Int64, Convert.ToInt64(dtOut.Rows[i][2]));
                dbHelper.ExecuteNonQuery(cmd);
            }
            else
            {
                string strTray_ID = dtOut.Rows[i][3].ToString();
                string strSBH = strTray_ID.Substring(1, 2);
                string strDH = strTray_ID.Substring(3, 2);

                cmd = dbHelper.GetStoredProcCommond("[SP_UNPACKAGE_ALL_2000]");
                dbHelper.AddInParameter(cmd, "@ContainerID", DbType.String, dtOut.Rows[i][4].ToString());
                dbHelper.AddInParameter(cmd, "@SEC_MAT_ID", DbType.String, dtOut.Rows[i][5].ToString());
                dbHelper.AddInParameter(cmd, "@MAT_NUM", DbType.Decimal, Convert.ToDecimal(dtOut.Rows[i][1]));
                dbHelper.AddInParameter(cmd, "@DETAILPID", DbType.String, detailPID);
                dbHelper.AddInParameter(cmd, "@USERNAME", DbType.String, Request.Cookies["vNovaUserNo"].Value.ToString());
                dbHelper.AddOutParameter(cmd, "@RESNO", DbType.Int32, 100);
                dbHelper.AddOutParameter(cmd, "@RESMSG", DbType.String, 255);
                dbHelper.ExecuteNonQuery(cmd);

                strSQL = @"INSERT INTO TCommands_HZK(SBH,DH,STATUS) VALUES('" + strSBH + "','" + strDH + "',1)";
                cmd = dbHelper.GetSqlStringCommond(strSQL);
                dbHelper.ExecuteNonQuery(cmd);
            }
        }


        if (iFlag > 0)
        {
            cmd = dbHelper.GetStoredProcCommond("SP_GenerateOUTCMDS_Define");
            dbHelper.AddInParameter(cmd, "@EquipmentE", DbType.Int32, Convert.ToInt32(ddlSQIDE.SelectedValue.ToString()));
            dbHelper.AddInParameter(cmd, "@MEMO", DbType.String, "");
            dbHelper.AddInParameter(cmd, "@FORCE_PICK", DbType.Int16, 1);
            dbHelper.AddInParameter(cmd, "@USER_NAME", DbType.String, Request.Cookies["vNovaUserNo"].Value.ToString());
            dbHelper.AddOutParameter(cmd, "@RESNO", DbType.Int32, 100);
            dbHelper.AddOutParameter(cmd, "@ErrMsg", DbType.String, 255);
            dbHelper.ExecuteNonQuery(cmd);
            int iResNo = Convert.ToInt32(dbHelper.GetParameter(cmd, "@RESNO").Value.ToString());
            string strResMsg = dbHelper.GetParameter(cmd, "@ErrMsg").Value.ToString();
            if (iResNo > 0)
            {
                Label1.Text = "操作成功！";
            }
            else
            {
                Label1.Text = strResMsg.ToString();
                return;
            }
        }

        ClearGrid();

    }
    protected void gvStock_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbtn_StockNo = (LinkButton)e.Row.FindControl("lbtn_StockNo");

            string updateUrl = string.Format("javascript: document.getElementById('{1}').value=window.showModalDialog('UnDelDataList.aspx?Rom=" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "&strStockNo={0}', window, 'dialogWidth=850px;dialogHeight=500px;scroll:no;resizable:no;status:0;');document.URL=location.href;", lbtn_StockNo.CommandArgument.ToString(), hiddenStock.ClientID);
            lbtn_StockNo.Attributes.Add("onclick", updateUrl);

        }
    }
    protected void gv_SelectedIndexChanged(object sender, EventArgs e)
    {
        int rowIndex=gv.SelectedIndex;
        decimal num = Convert.ToDecimal(gv.Rows[rowIndex].Cells[4].Text) - Convert.ToDecimal(gv.Rows[rowIndex].Cells[5].Text);
        if (num < 0)
        {
            num = 0;
        }
        gv.Rows[rowIndex].Style.Add(HtmlTextWriterStyle.BackgroundColor, "LightPink");
        BindGridStorage(gv.Rows[rowIndex].Cells[3].Text, gv.Rows[rowIndex].Cells[6].Text,num);
    }

    private void BindGridStorage(string strMatCode,string delPID,decimal num)
    {
        string WCode = Request.Cookies["WType"].Value;

        strSQL = @"Select TBM.Mat_Code,TBM.Mat_Name,TBZ.Zone_Name,TRP.Pos_ID,TBS.PID,TBI.S01,TBI.TS01,TBI.DynamicState02,
                    TBI.S02,TBI.S04,TBM.TM02,TBM.TM03,TBS.Mat_Num,TBZ.Structure,@delPID as delPID,TBS.CDT,@num as Num,TBS.ContainerID,TBS.Sec_Mat_ID,TRP.Tray_ID
                   from TBase_Storage TBS 
                    LEFT JOIN TBase_Interface TBI ON TBS.Sec_Mat_ID = TBI.Sec_Mat_ID 
                    LEFT JOIN  TBase_Material TBM ON TBM.Mat_Code = TBI.Mat_Code  
                    LEFT JOIN  TRel_TrayPosContainer TRT ON TRT.ContainerID = TBS.ContainerID 
                    LEFT JOIN TBase_TrayPos TBT ON TBT.Relations_ID = TRT.Relations_ID 
                    LEFT JOIN TRelations TRP ON TRP.Tray_ID = TBT.Tray_ID 
                    LEFT JOIN TBase_Position TBP ON TBP.Pos_ID = TRP.Pos_ID 
                    LEFT JOIN TBase_Zone TBZ ON TBZ.Zone_ID = TBP.Zone_ID  
                    Where  TRP.Pos_ID !='200000000000' and TBM.Mat_Code = '" + strMatCode.ToString() + "' and (TBI.S01='"+WCode+"' or 'FSSC'='"+WCode+"') order by TBS.CDT ";//TRP.Pos_ID !='200000000000' and
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        dbHelper.AddInParameter(cmd, "@delPID", DbType.String, delPID);
        dbHelper.AddInParameter(cmd, "@num", DbType.Decimal, num);
        gvStorage.DataSource = dbHelper.ExecuteDataTable(cmd);
        gvStorage.DataBind();

    }
    protected void btn_CKDXF_Click(object sender, ImageClickEventArgs e)
    {

        GridViewRow dv = null;
        for (int i = 0; i < gvStorage.Rows.Count; i++)
        {
            CheckBox cbx = (CheckBox)gvStorage.Rows[i].FindControl("chkSelect");
            if (cbx.Checked)
            {
                dv = gvStorage.Rows[i];

                TextBox txtNum = (TextBox)dv.FindControl("txtNum");
                Label labTray_ID = (Label)dv.FindControl("lab_Tray_ID");

                Label labContainerID = (Label)dv.FindControl("lab_ContainerID");

                Label labSEC_MAT_ID = (Label)dv.FindControl("lab_SEC_MAT_ID");

                Label lbl_Mat_Code = (Label)dv.FindControl("lbl_Mat_Code");

                Label lbl_Num = (Label)dv.FindControl("lbl_Num");

                strSQL = @"INSERT INTO [dbo].[Tmp_DelStorage]
                                       ([PID]
                                       ,[Mat_Code]
                                       ,[Mat_Name]
                                       ,[Mat_Num]
                                       ,[Out_Num]
                                       ,[Pos_ID]
                                       ,[Tray_ID]
                                       ,[ContainerID]
                                       ,[SEC_MAT_ID]
                                       ,[delPID]
                                       ,[N01])
                                 VALUES
                                       (@PID
                                       ,@Mat_Code
                                       ,@Mat_Name
                                       ,@Mat_Num
                                       ,@Out_Num
                                       ,@Pos_ID
                                       ,@Tray_ID
                                       ,@ContainerID
                                       ,@SEC_MAT_ID
                                       ,@delPID,@N01) ";

                cmd = dbHelper.GetSqlStringCommond(strSQL);
                dbHelper.AddInParameter(cmd, "@PID", DbType.String, gvStorage.DataKeys[i].Values[0].ToString());
                dbHelper.AddInParameter(cmd, "@Mat_Code", DbType.String, lbl_Mat_Code.Text);
                dbHelper.AddInParameter(cmd, "@Mat_Name", DbType.String, dv.Cells[1].Text);
                dbHelper.AddInParameter(cmd, "@Mat_Num", DbType.Decimal, Convert.ToDecimal(dv.Cells[4].Text));
                dbHelper.AddInParameter(cmd, "@Out_Num", DbType.Decimal, Convert.ToDecimal(txtNum.Text));
                dbHelper.AddInParameter(cmd, "@Pos_ID", DbType.Int64, Convert.ToInt64(dv.Cells[3].Text));
                dbHelper.AddInParameter(cmd, "@Tray_ID", DbType.String, labTray_ID.Text);
                dbHelper.AddInParameter(cmd, "@ContainerID", DbType.String, labContainerID.Text);
                dbHelper.AddInParameter(cmd, "@SEC_MAT_ID", DbType.String, labSEC_MAT_ID.Text);
                dbHelper.AddInParameter(cmd, "@N01", DbType.Decimal, Convert.ToDecimal(lbl_Num.Text));

                dbHelper.AddInParameter(cmd, "@delPID", DbType.String, gvStorage.DataKeys[i].Values[1].ToString());
                dbHelper.ExecuteNonQuery(cmd);
            }
        }

        BindGridDate();
    }

    private void BindGridDate()
    {
        strSQL = @"SELECT [Guid]
                          ,[PID]
                          ,[Mat_Code]
                          ,[Mat_Name]
                          ,[Mat_Num]
                          ,[Out_Num]
                          ,[Pos_ID]
                          ,[Tray_ID]
                          ,[S01]
                          ,[S02]
                          ,[S03]
                          ,[S04]
                          ,[S05]
                          ,[S06]
                          ,[S07]
                          ,[S08]
                          ,[TM02]
                          ,[TM03]
                          ,[ContainerID]
                          ,[SEC_MAT_ID]
                          ,[delPID]
                      FROM [dbo].[Tmp_DelStorage] order by Tray_ID";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        this.gvDate.DataSource = dbHelper.ExecuteDataTable(cmd);
        gvDate.DataBind();
    }


    private void ClearGrid()
    {
        strSQL = @" DELETE FROM [dbo].[Tmp_DelStorage]";
        cmd = this.dbHelper.GetSqlStringCommond(strSQL);
        dbHelper.ExecuteNonQuery(cmd);
        gvDate.DataSource = null;
        gvDate.DataBind();
    }
}
